import type{PiniaPluginContext} from 'pinia' 
import  {storePrefix} from "../config"
import {toRaw} from "vue"
import {type bsType,bs } from '@/common/utils'

type storeWayConfigType={
  [key:string]:'localStorage'| 'sessionStorage' | number   // 是number则为 bs 存储方式，值为有效时间
}
export function storagefy(storeWayConfig:storeWayConfigType){
  
  return (ctx:PiniaPluginContext)=>{
    let storage:Storage|bsType
    const storeWay=storeWayConfig[ctx.store.$id]
    if(storeWay||storeWay==0) storage=storeWay=="localStorage"?localStorage:storeWay=="sessionStorage"?sessionStorage:bs
    else return
     ctx.store.$subscribe(()=>{
       if(Object.keys(storeWayConfig).includes(ctx.store.$id)){
        if(!(storage instanceof Storage) && typeof storeWay=='number')
        storage.setItem(`${storePrefix}_${ctx.store.$id}`,JSON.stringify(toRaw(ctx.store.$state)),storeWay)
        else
        storage.setItem(`${storePrefix}_${ctx.store.$id}`,JSON.stringify(toRaw(ctx.store.$state)))
      }
      },{detached:true})
      // 初始化值
      if(Object.keys(storeWayConfig).includes(ctx.store.$id))
      {  
        try {
          const data=JSON.parse(storage.getItem(`${storePrefix}_${ctx.store.$id}`) as any)
          if(data) return data 
        } catch (error) {
          if(import.meta.env.VITE_NODE_ENV == 'dev')
          console.log("pinia持久化的数据损坏",ctx.store.$id)
        }
      }
  
  }
}
